package com.guodi.model.controller;

import com.guodi.common.utils.AjaxResult;
import com.guodi.core.secure.utils.AuthUtil;
import com.guodi.map.entity.MapDivision;
import com.guodi.map.feign.IMapClient;
import com.guodi.model.service.IMdlModelExportService;
import com.guodi.model.utils.FileUtil;
import com.guodi.system.feign.ISysClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @描述: 模型导出文档 控制类
 * @作者: 陈宏成
 * @日期: 2021/02/03 10:10:10
 **/
@RestController
@RequestMapping("/MdlModelExport")
@Api(value = "API - MdlModelExportController", description = "模型导出文档控制类",tags = "模型导出文档控制类")
public class MdlModelExportController {

    @Resource
    private IMdlModelExportService iMdlModelExportService;

    @Resource
    private IMapClient iMapClient;

    @Resource
    private ISysClient iSysClient;




    /**
     * @描述: （环境资源承载能力监测--动态评估）导出【资源环境承载能力报告动态评估报告.docx】
     * 使用模板：【动态评估】资源环境承载动态评估导出.docx
     * @作者: 陈宏成
     * @日期: 2021/02/04 10:10:10
     **/
    @PostMapping("/exportEnvironmentalLoadAssessmentWord")
    @ApiOperation(value = "导出【资源环境承载能力报告动态评估报告.docx】")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modelTypeCode", value = "模型体系编码", required = true, dataType = "string",paramType = "query", example = "dynamic-evaluate"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码",required = true, dataType = "string", paramType = "query",example = "441203"),
            @ApiImplicitParam(name = "year", value = "年份", dataType = "int",required = true,  paramType = "query",example = "2018"),
            @ApiImplicitParam(name = "keyWord", value = "关键字", dataType = "string", paramType = "query")
    })
    public void exportEnvironmentalLoadAssessmentWord (HttpServletResponse response, String modelTypeCode, String divisionCode, String year , String keyWord){
        MapDivision division = iMapClient.mateByCode(divisionCode);
        String divisionText = division == null ? "" : division.getName();
        String docxFileUrl = null;
        try{
            // word文档
            String docxName = this.iMdlModelExportService.exportEnvironmentalLoadAssessmentWord(modelTypeCode, divisionCode, year, keyWord);
            docxFileUrl = FileUtil.tempFilePath + docxName;
            // 文件名
            String newExportFileName = divisionText + "资源环境承载能力报告动态评估报告（"+ year +"年）" ;
            // 导出
            InputStream inputStream = new FileInputStream(docxFileUrl);
            response.setContentType("application/octet-stream;charset=UTF-8;");
            response.setHeader("Content-Disposition", "attachment; filename=\"" +  new String(newExportFileName.getBytes(),"iso-8859-1") + ".docx"+ "\"");
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0){
                outputStream.write(bytes,0,len);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(docxFileUrl != null){
                FileUtil.deleteFile(docxFileUrl);
            }
        }
    }


    /**
     * @描述: （监测评估预警--专题评估--专项评估）导出【专题评估报告.docx】
     * 使用模板：【专题评估】专题评估导出报告.docx
     * @作者: 陈宏成
     * @日期: 2021/02/03 10:10:10
     **/
    @PostMapping("/exportThematicAssessmentWord")
    @ApiOperation(value = "导出【专题评估报告.docx】")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modelTypeCode", value = "模型体系编码", required = true, dataType = "string",paramType = "query", example = "special-evaluate"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码",required = true, dataType = "string", paramType = "query",example = "441203"),
            @ApiImplicitParam(name = "year", value = "年份", dataType = "int",required = true,  paramType = "query",example = "2018"),
            @ApiImplicitParam(name = "keyWord", value = "关键字", dataType = "string", paramType = "query")
    })
    public void exportThematicAssessmentWord (HttpServletResponse response, String modelTypeCode, String divisionCode, String year , String keyWord){
        MapDivision division = iMapClient.mateByCode(divisionCode);
        String divisionText = division == null ? "" : division.getName();
        String docxFileUrl = null;
        try{
            // word文档
            String docxName = this.iMdlModelExportService.exportThematicAssessmentWord(modelTypeCode, divisionCode, year, keyWord);
            docxFileUrl = FileUtil.tempFilePath + docxName;
            // 文件名
            String newExportFileName = divisionText + "专题评估报告（"+ year +"年）" ;
            // 导出
            InputStream inputStream = new FileInputStream(docxFileUrl);
            response.setContentType("application/octet-stream;charset=UTF-8;");
            response.setHeader("Content-Disposition", "attachment; filename=\"" +  new String(newExportFileName.getBytes(),"iso-8859-1") + ".docx"+ "\"");
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0){
                outputStream.write(bytes,0,len);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(docxFileUrl != null){
                FileUtil.deleteFile(docxFileUrl);
            }
        }
    }
    /**
     * @作者: 林楷 2021/4/29
     * @描述: 资源环境承载能力检测--决策支持--导出报告）
     * 导出【资源环境承载能力决策分析报告.docx】
     * @参数: modelTypeCode 模型体系编码
     * @参数: divisionCode 行政区划代码
     * @参数: year 年份
     */
    @PostMapping("/exportDecisionAnalysisReportWord")
    @ApiOperation(value = "导出【资源环境承载能力决策分析报告.docx】")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modelTypeCode", value = "模型体系编码", required = true, dataType = "string",paramType = "query", example = "special-evaluate"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码",required = true, dataType = "string", paramType = "query",example = "441203"),
            @ApiImplicitParam(name = "year", value = "年份", dataType = "int",required = true,  paramType = "query",example = "2018")
    })
    public void exportDecisionAnalysisReportWord(HttpServletResponse response, String modelTypeCode, String divisionCode, Integer year) {
        MapDivision division = iMapClient.mateByCode(divisionCode);
        String divisionText = division == null ? "" : division.getName();
        String docxFileUrl = null;
        // word文档
        try {
            String docxName = this.iMdlModelExportService.exportDecisionAnalysisReportWord(modelTypeCode, divisionCode, year);
            docxFileUrl = FileUtil.tempFilePath + docxName;
            // 文件名
            String newExportFileName = divisionText + "专题评估报告（"+ year +"年）" ;
            // 导出
            InputStream inputStream = new FileInputStream(docxFileUrl);
            response.setContentType("application/octet-stream;charset=UTF-8;");
            response.setHeader("Content-Disposition", "attachment; filename=\"" +  new String(newExportFileName.getBytes(),"iso-8859-1") + ".docx"+ "\"");
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0){
                outputStream.write(bytes,0,len);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (StringUtils.isNotBlank(docxFileUrl)){
                new File(docxFileUrl).delete();
            }
        }
    }


    /**

模型体系目录结构：

潜力评估结果--------------------（这层目录的名称无所谓，但是根节点只能有一个，因为只会导出第一个根节点的数据）
     农业生产潜力--------------------（这一目录名称有要求，必须是以农业开头：“农业xxxxxx”）
          农业生产适宜区内生态保护红线--------------（这一层的目录有要求，必须是指定格式：“xxxxx内xxxxx”，前者为一个范围，后者为这个范围内分析的对象，这两个字段会在报告中体现）
               潜力分析_农业开发高中低适宜区内生态红线_监测值--------------（这一层是模型，别名随意，3.3分支要和modelStatConfig.json中对应）
     建设生产潜力--------------------（这一目录名称有要求，必须是以建设开头：“建设xxxxxx”）
          建设开发适宜区内生态保护红线--------------（这一层的目录有要求，必须是指定格式：“xxxxx内xxxxx”，前者为一个范围，后者为这个范围内分析的对象，这两个字段会在报告中体现）
               潜力分析_建设开发高中低适宜区内生态保护红线_监测值--------------（这一层是模型，别名随意，3.3分支要和modelStatConfig.json中对应）

     * @作者: 陈宏成 2022-04-14
     * @描述: 规划分析评价——潜力评估——导出潜力评估报告
     * 导出【潜力评估报告.docx】
     * @参数: modelTypeCode 模型体系编码
     * @参数: divisionCode 行政区划代码
     * @参数: year 年份
     */
    @PostMapping("/exportPotentialAssessmentWord")
    @ApiOperation(value = "导出【资源环境承载能力决策分析报告.docx】")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "modelTypeCode", value = "模型体系编码", required = true, dataType = "string",paramType = "query", example = "special-evaluate"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码",required = true, dataType = "string", paramType = "query",example = "441203"),
            @ApiImplicitParam(name = "year", value = "年份", dataType = "int",required = true,  paramType = "query",example = "2018")
    })
    public void exportPotentialAssessmentWord(HttpServletResponse response, String modelTypeCode, String divisionCode, Integer year) {
        MapDivision division = iMapClient.mateByCode(divisionCode);
        String divisionText = division == null ? "" : division.getName();
        String docxFileUrl = null;
        // word文档
        try {
            String docxName = this.iMdlModelExportService.exportPotentialAssessmentWord(modelTypeCode, divisionCode, year);
            docxFileUrl = FileUtil.tempFilePath + docxName;
            // 文件名
            String newExportFileName = divisionText + "潜力评估报告（"+ year +"年）" ;
            // 导出
            InputStream inputStream = new FileInputStream(docxFileUrl);
            response.setContentType("application/octet-stream;charset=UTF-8;");
            response.setHeader("Content-Disposition", "attachment; filename=\"" +  new String(newExportFileName.getBytes(),"iso-8859-1") + ".docx"+ "\"");
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0){
                outputStream.write(bytes,0,len);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (StringUtils.isNotBlank(docxFileUrl)){
                new File(docxFileUrl).delete();
            }
        }
    }

    /**
     * @描述: 专规审查导出报告
     * @作者: 李杭
     * @日期: 2022/07/08
     **/
    @PostMapping("/exportSpecialRegulationsReviewWord")
    @ApiOperation(value = "专规审查导出报告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "规划名称", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "jsonData", value = "json数据", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "divisionCode", value = "行政区划代码",required = true, dataType = "string", paramType = "query",example = "441203")
    })
    public AjaxResult exportSpecialRegulationsReviewWord(HttpServletResponse response, String name, String jsonData, String divisionCode) {
        // word文档
        String deptId = AuthUtil.getDeptId();
//        String deptName = iSysClient.getDeptName(Long.parseLong(deptId)).getData();
        String docxFileUrl = null;
        String pdf = null;
        try {
//            String docxName = iMdlModelExportService.exportSpecialRegulationsReviewWord(jsonData, name, divisionCode, deptName);
//            docxFileUrl = FileUtil.tempFilePath + docxName;
//             文件名
//            String newExportFileName = "专规审查报告" ;
//            NewWordUtil.doc2pdf(new File(docxFileUrl), FileUtil.tempFilePath + newExportFileName + ".pdf");
//             导出
//            pdf = FastDFSUtil.upload(IOUtils.toByteArray(new FileInputStream(FileUtil.tempFilePath + newExportFileName + ".pdf")), "pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (StringUtils.isNotBlank(docxFileUrl)){
                new File(docxFileUrl).delete();
            }
        }
        return new AjaxResult(pdf);
    }

}
